package com.atguigu.gulimall.seckill.service.imp;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.seckill.feign.CouponFeignService;
import com.atguigu.gulimall.seckill.feign.ProductFeignService;
import com.atguigu.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.seckill.service.SeckillService;
import com.atguigu.gulimall.seckill.to.SecKillSkuRedisTo;
import com.atguigu.gulimall.seckill.vo.SecKillSessionsWithSkus;
import com.atguigu.gulimall.seckill.vo.SecKillSkuVo;
import com.atguigu.gulimall.seckill.vo.SkuInfoVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SeckillServiceImp implements SeckillService {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    RedissonClient redissonClient;

    private final String SESSION_CACHE_PREFIX = "seckill:sessions:";
    private final String SKUKILL_CHCHE_PREFIX = "seckill:skus";

    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";


    /**
     * 每天晚上3点，上架最近三天的秒杀商品
     * 当天00:00:00 - 23:59:59
     * 明天00:00:00 - 23:59:59
     * 后面00:00:00 - 23:59:59
     */
    @Override
    public void uploadSeckillSkuLatest3Days() {
        //1、远程调用->coupon服务，扫描数据库，查询最近3天需要上架的商品
        R r = couponFeignService.getLates3DaySession();
        if (r != null && r.getCode() == 0) {
            List<SecKillSessionsWithSkus> data = r.getData(new TypeReference<List<SecKillSessionsWithSkus>>() {
            });
            //2、将数据缓存到redis
            //2.1）、缓存活动信息
            saveSessionInfos(data);
            //2.2）、缓存活动关联的商品信息
            saveSessionSkuInfos(data);
        }
    }

    /**
     * 返回当前时间可以参与的秒杀商品信息
     */
    @Override
    public List<SecKillSkuRedisTo> getCurrentSeckillSkus() {

        //1、确定当前时间属于哪个秒杀场次
        Date date = new Date();
        long nowTime = date.getTime();


        //TODO Sentinel自义定资源
        try (Entry entry = SphU.entry("SeckillSkus")) {
            //TODO 业务代码
            //2、在redis中查询key符合 seckill:sessions:* 的所有key组成的集合
            Set<String> keys = stringRedisTemplate.keys(SESSION_CACHE_PREFIX + "*");//key组成的集合
            if (keys != null && keys.size() > 0) {
                for (String key : keys) {
                    //seckill:sessions:1618272000000_1618279200000
                    String replace = key.replace(SESSION_CACHE_PREFIX, "");
                    String[] s = replace.split("_");
                    long start = Long.parseLong(s[0]);
                    long end = Long.parseLong(s[1]);
                    if (nowTime >= start && nowTime <= end) {
                        //3、获取当前秒杀场次下的商品信息
                        List<String> range = stringRedisTemplate.opsForList().range(key, -100, 100);//当前key对应的所有val值
                        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(SKUKILL_CHCHE_PREFIX);
                        List<String> list = hashOps.multiGet(range);//所有商品信息的json字符串
                        if (list != null && list.size() > 0) {
                            List<SecKillSkuRedisTo> collect = list.stream().map(item -> {
                                SecKillSkuRedisTo to = JSON.parseObject(item, SecKillSkuRedisTo.class);
                                return to;
                            }).collect(Collectors.toList());
                            return collect;
                        }
                        break;
                    }
                }
            }
        } catch (BlockException ex) {
            //TODO 资源访问阻止，被限流或被降级，在此处进行相应的处理操作
            log.info("自定义资源触发降级或限流....");
        }

        //自义定资源 resourceName是自义定的资源名
        try (Entry entry = SphU.entry("resourceName")) {
            // 被保护的业务逻辑
            // do something here...
        } catch (BlockException ex) {
            // 资源访问阻止，被限流或被降级
            // 在此处进行相应的处理操作
        }


        return null;
    }

    /**
     * 根据skuId获取该商品的秒杀信息
     */
    @Override
    public SecKillSkuRedisTo getskuSeckillInfo(Long skuId) {

        BoundHashOperations<String, String, String> ops = stringRedisTemplate.boundHashOps(SKUKILL_CHCHE_PREFIX);
        //1、获取所有参与秒杀的商品的key
        Set<String> keys = ops.keys();
        if (keys != null && keys.size() > 0) {
            //遍历，并通过正则表达式找到目标商品
            String regx = "\\d_" + skuId;
            for (String key : keys) {
                if (Pattern.matches(regx, key)) {
                    //匹配上，则获取其val值，即商品的秒杀信息
                    String s = ops.get(key);
                    SecKillSkuRedisTo skuInfo = JSON.parseObject(s, SecKillSkuRedisTo.class);
                    //随机码处理
                    Long startTime = skuInfo.getStartTime();
                    Long endTime = skuInfo.getEndTime();
                    long nowTime = new Date().getTime();
                    if (nowTime >= startTime && nowTime <= endTime) {
                    } else {
                        skuInfo.setRandomCode(null);
                    }
                    return skuInfo;
                }
            }
        }
        return null;
    }

    /**
     * 秒杀功能
     */
    @Override
    public String kill(String killId, String key, Integer num) {

        MemberRespVo respVo = LoginUserInterceptor.threadLocal.get();

        //1、获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(SKUKILL_CHCHE_PREFIX);
        String json = hashOps.get(killId);
        if (StringUtils.isEmpty(json)) {
            return null;
        } else {
            SecKillSkuRedisTo redis = JSON.parseObject(json, SecKillSkuRedisTo.class);
            //校验合法性
            //1、校验时间合法性
            Long startTime = redis.getStartTime();
            Long endTime = redis.getEndTime();
            long time = new Date().getTime();
            if (time >= startTime && time <= endTime) {
                //2、校验随机码和商品id
                String randomCode = redis.getRandomCode();
                String skuId = redis.getPromotionSessionId() + "_" + redis.getSkuId();
                if (randomCode.equals(key) && killId.equals(skuId)) {
                    //3、验证购物数量是否合理
                    if (num <= redis.getSeckillLimit().intValue()) {
                        //4、验证这个人是否已经购买过了。幂等性：只要秒杀成功，就去redis占位。 userId_SessionId_skuId
                        //Redis底层的setnx()方法，不存在才会创建，否则返回false。
                        String redisKey = respVo.getId() + "_" + skuId;
                        //自动过期
                        Long ttl = endTime - startTime;
                        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (aBoolean) {
                            //占位成功，代表没买过
                            //5、信号量
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);

                            //尝试获取num个信号量。  成功返回true，失败false
                            boolean b = semaphore.tryAcquire(num);
                            if (b) {
                                //秒杀成功
                                //快速下单，发送MQ消息
                                String timeId = IdWorker.getTimeId();
                                SeckillOrderTo orderTo = new SeckillOrderTo();
                                orderTo.setOrderSn(timeId);
                                orderTo.setMemberId(respVo.getId());
                                orderTo.setNum(num);
                                orderTo.setPromotionSessionId(redis.getPromotionSessionId());
                                orderTo.setSkuId(redis.getSkuId());
                                orderTo.setSeckillPrice(redis.getSeckillPrice());
                                //给MQ发送消息
                                rabbitTemplate.convertAndSend("order-event-exchange",
                                        "order.seckill.order",
                                        orderTo);
                                return timeId;
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

    /**
     * 缓存活动信息到redis中
     */
    private void saveSessionInfos(List<SecKillSessionsWithSkus> sessions) {
        sessions.stream().forEach(item -> {
            long startTime = item.getStartTime().getTime();
            long endTime = item.getEndTime().getTime();
            String key = SESSION_CACHE_PREFIX + startTime + "_" + endTime;

            //缓存活动信息
            //缓存前，先判断是否已经存在相同的key（保证幂等性）
            Boolean hasKey = stringRedisTemplate.hasKey(key);
            if (!hasKey) {
                //不存在，才执行缓存
                List<String> collect = item.getRelationSkus().stream().map(sku -> {
                    return sku.getPromotionSessionId().toString() + "_" + sku.getSkuId().toString(); // 场次id_skuId
                }).collect(Collectors.toList());
                stringRedisTemplate.opsForList().leftPushAll(key, collect);
            }
        });
    }

    /**
     * 缓存活动关联的商品信息到redis中
     */
    private void saveSessionSkuInfos(List<SecKillSessionsWithSkus> sessions) {
        //准备hash操作
        BoundHashOperations<String, Object, Object> ops = stringRedisTemplate.boundHashOps(SKUKILL_CHCHE_PREFIX);
        sessions.stream().forEach(session -> {
            session.getRelationSkus().stream().forEach(item -> {
                //生成一个随机码
                String token = UUID.randomUUID().toString().replace("-", "");

                //先判断，再缓存商品信息（保证幂等性）
                if (!ops.hasKey(item.getPromotionSessionId().toString() + "_" + item.getSkuId().toString())) {
                    SecKillSkuRedisTo to = new SecKillSkuRedisTo();
                    //1、sku的基本信息
                    //远程调用->product服务，查询sku信息
                    R r = productFeignService.getSkuInfo(item.getSkuId());
                    if (r.getCode() == 0) {
                        SkuInfoVo data = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        to.setSkuInfo(data);
                    }

                    //2、sku的秒杀信息
                    BeanUtils.copyProperties(item, to);

                    //3、设置当前商品的秒杀时间信息
                    to.setStartTime(session.getStartTime().getTime());
                    to.setEndTime(session.getEndTime().getTime());

                    //4、商品的随机码（防止恶意软件抢货）
                    to.setRandomCode(token);
                    //缓存商品信息
                    String jsonString = JSON.toJSONString(to);
                    ops.put(item.getPromotionSessionId().toString() + "_" + item.getSkuId().toString(), jsonString);

                    //5、使用sku的库存作为分布式信号量（redisson） 限流
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    //被秒杀商品的库存量作为信号量
                    semaphore.trySetPermits(item.getSeckillCount().intValue());
                }
            });
        });
    }
}
